package Demo75;

import Demo53.ListNode;
import org.w3c.dom.Node;
/**
 * 二叉树的锯齿形层序遍历
 * https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/
 */

import java.util.*;

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) return ret;
        // 创建一个队列
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int count = 1;
        while(!q.isEmpty()) {
            int sz = q.size();
            List<Integer> tmp = new ArrayList<>(); // 统计返回的值
            for(int i = 0; i < sz; i++) {
                TreeNode node = q.poll();
                tmp.add(node.val); // 获取节点值,放入链表
                if(node.left != null) q.add(node.left);
                if(node.right != null) q.add(node.right);
            }
            if(count % 2 == 0) Collections.reverse(tmp);
            count++;
            ret.add(tmp);
        }
        return ret;
    }
}